<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="1000px"
      @close="cancelSubmit"
    >
      <div class="content">
        <div class="content-left">
          <div class="search-wrap">
            <div class="it" :title="`基站名称：${info.name}`">
              {{ `基站名称：${info.name}` }}
            </div>
            <div class="it" :title="`SN码：${info.sn}`">
              {{ `SN码：${info.sn}` }}
            </div>
          </div>
          <div class="tree-wrap">
            <el-tree
              :data="treedata"
              show-checkbox
              default-expand-all
              node-key="nodeId"
              ref="tree"
              highlight-current
              :filter-node-method="filterNode"
              :check-on-click-node="true"
              :expand-on-click-node="false"
              @check-change="treeCheckChange"
              :props="defaultProps"
            >
            </el-tree>
          </div>
        </div>
        <div class="content-center">
          <!-- <i class="el-icon-d-arrow-right" @click="selectNode"></i> -->
        </div>
        <div class="content-right">
          <div class="add-num">{{ `已添加${selectNodes.length}` }}</div>
          <div v-if="selectNodes.length === 0">
            <el-empty description="暂无数据"></el-empty>
          </div>
          <div
            v-else
            v-for="node in selectNodes"
            :key="node.id"
            class="select-item"
          >
            <!-- <span :title="`${node.name}(${node.id})【${node.parentName}】`">{{
              `${node.name}【${node.parentName}】`
            }}</span> -->
            <span :title="node.name" class="name">{{ node.name }}</span>
            <span :title="node.parentName" class="parentName">{{
              node.parentName
            }}</span>
            <i class="el-icon-close" @click="deleteNode(node)"></i>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancelSubmit">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash';
import { getSchoolTree } from '@/api/setClass.js';
import { baseStationBindClass, getBaseStationDetail } from '@/api/baseStation';
import { ERROR_CODE } from '@/api/api.js';
const DEFAULT_LEVEL = 2;
export default {
  data() {
    return {
      name: 'ljq',
      visible: false,
      info: {
        baseStationId: '',
        classList: [],
        name: '',
        sn: '',
      },
      schoolList: [],
      // 树的数据数组
      treedata: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      selectNodes: [],
      initTreeFlag: false,
    };
  },
  props: {
    title: {
      type: String,
      default: '绑定班级',
    },
    classId: {
      type: [String, Number],
      default: '',
    },
    schoolId: [String, Number],
  },
  computed: {
    selectNodesIds() {
      console.log(
        'selectNodesIds',
        this.selectNodes.map((item) => item.id)
      );
      return this.selectNodes.map((item) => {
        return `${DEFAULT_LEVEL}_${item.id}`;
      });
    },
    canSetTree() {
      return {
        selectNodesIds: this.selectNodesIds,
        initTreeFlag: this.initTreeFlag,
      };
    },
  },
  watch: {
    canSetTree() {
      console.log('canSetTree', this.canSetTree, this.selectNodesIds);
      if (this.initTreeFlag && this.selectNodesIds.length) {
        setTimeout(() => {
          this.$refs.tree &&
            this.$refs.tree.setCheckedKeys(this.selectNodesIds);
        }, 88);
      }
    },
  },
  methods: {
    getBaseDetail(row) {
      getBaseStationDetail({
        schoolId: this.schoolId,
        baseStationId: row.baseStationId,
      }).then((res) => {
        if (res[0]) {
          return;
        }
        let data = res[1];
        if (data.data && data.code === 0) {
          this.info = data.data;
          this.selectNodes = this.info.classList.map((item) => {
            return {
              id: item.classId,
              name: item.className,
              parentName: item.gradeName,
            };
          });
        }
      });
    },
    // 取消提交
    cancelSubmit() {
      this.treedata = [];
      this.selectNodes = [];
      this.visible = false;
      this.$refs.tree.setCheckedKeys([]);
    },
    submit() {
      let params = {
        schoolId: this.schoolId,
        baseStationId: this.info.baseStationId,
        classIdList: this.selectNodes.map((item) => item.id),
      };
      // if (this.selectNodesIds.length === 0) {
      //   return this.$message.info('请选择绑定的班级！')
      // }
      baseStationBindClass(params).then((res) => {
        if (res[0]) {
          if (res[1].code === ERROR_CODE.REFRESH_LIST) {
            this.$emit('refreshList');
            this.cancelSubmit();
          }
          return;
        }
        if (res[1] && res[1].code == 0) {
          this.$message.success('保存成功');
          setTimeout(() => {
            this.$emit('refreshList');
            this.cancelSubmit();
          }, 1500);
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      let hasChild = data.children.length > 0;
      let flag = false;
      if (data.level === DEFAULT_LEVEL) {
        flag = data.name.indexOf(value) !== -1;
      } else {
        flag = data.children.length > 0;
      }
      return flag;
    },
    // 初始化树节点列表
    init(row) {
      this.info = row;
      // this.getBaseDetail(row);
      this.selectNodes = this.info.classList.map((item) => {
        return {
          id: item.classId,
          name: item.className,
          parentName: item.gradeName,
        };
      });
      let params = {
        schoolId: this.schoolId,
        layer: DEFAULT_LEVEL,
      };
      this.initTreeFlag = false;
      // 获取学校数据
      getSchoolTree(params).then((res) => {
        if (res[1] && res[1].code == 0) {
          // const showData = this.filterNotChildNodes(res[1].data.gradeList || []); // todo
          // console.log('showData:', showData);
          this.initTreeFlag = true;
          this.treedata = res[1].data.gradeList || [];
          this.visible = true;
        } else {
          // this.$message.info(res[1].msg)
        }
      });
    },
    filterNotChildNodes(treeData) {
      function eachItem(arr) {
        let res = arr.filter((item) => {
          if (item.children && item.children.length > 0) {
            item.children = eachItem(item.children);
          }
          return item.children.length;
        });
        return res.length ? res : [];
      }
      return eachItem(treeData);
    },
    treeCheckChange(data, checked, indeterminate) {
      console.log('check-change', data, checked, indeterminate);
      if (checked) {
        this.selectNode(data);
      } else {
        this.deleteNode(data);
      }
    },
    selectNode(node) {
      this.$nextTick(() => {
        let selectNodes = [node].filter((item) => item.level == DEFAULT_LEVEL);
        console.log('selectNode', selectNodes, this.selectNodes);
        if (!selectNodes.length) return;
        // 选择节点顺序最前面
        let isHasNode = this.selectNodes.filter((item) => item.id == node.id);
        console.log('isHasNode', isHasNode, this.selectNodes);
        if (!isHasNode.length) {
          this.selectNodes.unshift(node);
        }
      });
    },
    deleteNode(node) {
      // 删除node
      this.$refs.tree.setChecked(node, false);
      this.selectNodes = this.selectNodes.filter((item) => {
        return item.id !== node.id;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  height: 500px;
  &-left {
    margin: 10px;
    flex-basis: 58%;
    .search-wrap {
      .it {
        display: inline-block;
        margin: 0 5px;
        width: 45%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .tree-wrap {
      overflow: auto;
      height: calc(100% - 40px);
    }
  }
  &-center {
    flex-basis: 4%;
    display: flex;
    align-content: space-around;
    justify-content: space-around;
    align-items: center;
    i {
      cursor: pointer;
    }
  }
  &-right {
    margin: 10px;
    flex-basis: 38%;
    overflow: auto;
    .add-num {
      height: 36px;
      line-height: 36px;
      font-weight: 500;
    }
    .select-item {
      height: 36px;
      line-height: 36px;
      span {
        width: 80%;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      span.name {
        width: 50%;
      }
      span.parentName {
        width: 40%;
      }
      i {
        cursor: pointer;
        margin: 10px 0;
        vertical-align: top;
      }
    }
  }
}
</style>
